import crypto from '../utils/crypto';
import * as express from 'express';
import db from '../utils/db';
import http from '../utils/http';
import room_service from './room_service';




//获取类型声明//
import configs_win from '../configs_win';
const HALL_SERVER_TYPE = configs_win.hall_server();
type HST = typeof HALL_SERVER_TYPE;
//获取类型声明//

const app = express();
let config: HST = null;
const call_path = 'hall-server -> client_service -> 路由 <<';


app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", '3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});




export default class Client_service{

    /**
     * 9001端口
     * @param  
     */
    static start($config: HST){
        config = $config;
        app.listen(config.CLIENT_PORT);
        console.log('登录游戏的服务器端口号： ' + config.CLIENT_PORT);
    }

}

function check_account(req: express.Request, res: express.Response){
    const account = req.query.account;
    const sign = req.query.sign;
    if(account == null || sign == null){
        http.send(res, 1, call_path + req.path + '>>错误信息：account或sign为空');
        return false;
    }
    return true;
}

app.get('/login', function(req, res){

    if(!check_account(req, res)){
        return;
    }

    let ip = req.ip;
    if(ip.indexOf('::ffff:') != -1){
        ip = ip.substr(7);
    }

    let account = req.query.account;
    db.get_user_data(account, (data) => {

        if(data == null){
            http.send(res, 0, 'ok');
            return;
        }

        const ret = <ret>{
            account: data.account,
            userid: data.userid,
            name: data.name,
            lv: data.lv,
            exp: data.exp,
            coins: data.coins,
            gems: data.gems,
            ip: ip,
            sex: data.sex
        };
        
        db.get_room_id_of_user(data.userid, (roomid) => {

            if(roomid != null){//用户刚刚登录过，
                //检查房间是否存在于数据库中
                db.is_room_exist(roomid, (retval) => {
                    if(retval){
                        ret.roomid = roomid;
                    }
                    else{
                        //房间不在了，说明信息不同步了，清楚掉用户记录
                        db.set_id_of_user(data.userid, null);
                    }
                    http.send(res, 0, 'ok', ret);
                });
            }
            else{
                http.send(res, 0, 'ok', ret);
            }
        });
    });
});



//创建用户
app.get('/create_user', (req, res) => {
    
    if(!check_account(req, res)){
        return;
    }

    const account = req.query.account;
    const name = req.query.name;
    const coins = 1000;
    const gems = 21;
    console.log('用户名：' + name);

    db.is_user_exist(account, (ret) => {
        if(ret){
            http.send(res, 1, call_path + '/create_user,错误信息：' + '用户已经存在！');
        }
        else{
            db.create_user(account, name, coins, gems, 0, null, (ret) => {
                if(ret){
                    http.send(res, 0, 'ok');
                }
                else{
                    http.send(res, 2, call_path + '/create_user,错误信息：' + '创建用户出错');
                }
            });
        }
    });

});


app.get('/create_private_room', (req, res) => {

    const data = req.query;
    if (!check_account(req, res)){
        return;
    }
    
    const account = data.account;
    const conf = data.conf;
    data.account = null;
    data.sign = null;

    db.get_user_data(account, (data) => {
        if(data == null){
            http.send(res, 1, call_path + '/create_private_room,错误信息：' + '操作数据库出错');
            return;
        }
        const userId = data.userid;
        const name = data.name;
        //验证玩家状态
        db.get_room_id_of_user(userId, (roomId) => {
            if(roomId != null){
                http.send(res, -1, call_path + '/create_private_room,错误信息：' + '用户正在房间中玩耍');
                return;
            }
            //创建房间
            room_service.createRoom(account, userId, conf, (err, roomId) => {
                if(err == 0 && roomId != null){
                    room_service.enterRoom(userId, name, roomId, (errcode, enterInfo) => {
                        if(enterInfo){
                            let ret: ret = {
                                roomid: roomId,
                                ip: enterInfo.ip,
                                port: enterInfo.port,
                                token: enterInfo.token,
                                time: Date.now(),
                            };
                            ret.sign = crypto.md5(roomId + ret.token + ret.time + config.ROOM_PRI_KEY);
                            http.send(res, 0, 'ok', ret);
                        }
                        else{
                            http.send(res, errcode, call_path + '/create_private_room,错误信息：' + '进入房间失败');
                        }
                    });
                }
                else{
                    http.send(res, err, call_path + '/create_private_room,错误信息：创建房间失败');
                }
            });
        });
    });
});


app.get('/enter_private_room', (req, res) => {

    const data = req.query;
    const roomId = data.roomid;
    if(roomId == null){
        http.send(res, 1, call_path + '/enter_private_room,错误信息：' + '进入房间时roomid没有匹配到');
        return;
    }

    if (!check_account(req, res)){
        return;
    }

    const account = data.account;
    db.get_user_data(account, (data) => {

        if(data == null){
            http.send(res, -1, call_path + '/enter_private_room,错误信息：' + '使用accout查询t_users表时出错');
            return;
        }

        const userId = data.userid;
        const name = data.name;
        room_service.enterRoom(userId, name, roomId, (errcode, enterInfo) => {

            if(enterInfo){
                const ret: ret = {
                    roomid: roomId,
                    ip: enterInfo.ip,
                    port: enterInfo.port,
                    token: enterInfo.token,
                    time: Date.now(),
                };
                ret.sign = crypto.md5(roomId + ret.token + ret.time + config.ROOM_PRI_KEY);
                http.send(res, 0, 'ok', ret);
            }
            else{
                http.send(res, errcode, call_path + '/enter_private_room,错误信息：' + '进入房间失败');
            }
        });

    });
});


//使用account在t_users表中查找到gems信息并发送回去
app.get('/get_user_status', (req, res) => {
    if (!check_account(req, res)){
        return;
    }

    const account = req.query.account;
    db.get_gems(account, (data) => {
        if(data){
            http.send(res, 0, 'ok', {gems: data.gems});
        }
        else{
            http.send(res, 1, call_path + req.path + '错误信息：查找gems失败');
        }
    });
});


//获取公告信息及版本号
app.get('/get_message', (req, res) => {

    if(!check_account(req, res)){
        return;
    }

    const type = req.query.type;
    if(!type){
        http.send(res, -1, call_path + req.path + '错误信息：不带上type属性，我用什么给你查找信息啊？');
        return;
    }

    const version = req.query.version;
    db.get_message(type, version, (data) => {
        if(data){
            http.send(res, 0, 'ok', {msg: data.msg, version: data.version});
        }
        else{
            http.send(res, 1, call_path + req.path + ' 错误信息: 在t_message表中没有查到');
        }
    });

});
